package logic

import (
	"context"
	"doc-hub/models"
	"fmt"
	"gorm.io/gorm"

	"doc-hub/docrpc/docrpc"
	"doc-hub/docrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type DocUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDocUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DocUpdateLogic {
	return &DocUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改
func (l *DocUpdateLogic) DocUpdate(in *docrpc.DocUpdateRequest) (*docrpc.DocUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var doctor models.Doctor
	models.DB.Debug().Where("id =?", in.DoctorId).Find(&doctor)
	if doctor.ID == 0 {
		return nil, fmt.Errorf("当前医生不存在禁止修改")
	}

	var findDoctor models.Doctor
	models.DB.Debug().Where("name = ?", in.Name).Find(&findDoctor)
	if findDoctor.ID != 0 {
		return nil, fmt.Errorf("当前医生名称已存在修改失败")
	}

	doctor = models.Doctor{
		Model: gorm.Model{ID: uint(in.DoctorId)},
		Name:  in.Name,
		Image: in.Image,
		Job:   in.Job,
		Dep:   in.Dep,
	}

	models.DB.Debug().Updates(&doctor)

	return &docrpc.DocUpdateResponse{
		DoctorId: int64(doctor.ID),
	}, nil
}
